package com.ahuan.service.Impl;

import com.ahuan.domain.ModuleNode;
import com.ahuan.domain.Module;
import com.ahuan.mapper.ModuleMapper;
import com.ahuan.service.ModuleService;
import com.ahuan.utils.TreeBuilder;
import com.ahuan.utils.TreeBuilder1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ModuleServiceImpl implements ModuleService {
    @Autowired
    ModuleMapper moduleMapper;

    @Override
    public List<Module> getModuleTree() {
        List<Module> modules = moduleMapper.selectModuleList();
        System.out.println(modules);
//        TreeBuilder treeBuilder = new TreeBuilder(modules);
//        List<Module> modules1 = treeBuilder.buildTree("0");
        TreeBuilder1<Module> treeBuilder = new TreeBuilder1(modules,"id","pId","children");
        List<Module> tree = treeBuilder.buildTree("0"); // 传入根节点的 ID，这里假设根节点的 parentId 为 0
        TreeBuilder.printTree(tree,0);
        return tree;//假设一个不存在的结点id为0
    }

    @Override
    public List<Module> getModuleList() {
        List<Module> modules = moduleMapper.selectModuleList();
        return modules;//假设一个不存在的结点id为0
    }

    @Override
    public ModuleNode queryModuleMsg(String id) {
        return moduleMapper.selectModuleMsg(id);
    }

    @Override
    public boolean editNode(ModuleNode node) {
        return moduleMapper.updateNode(node) > 0;
    }

    @Override
    @Transactional
    public boolean addNode(ModuleNode moduleNode) {
        Module module = new Module(null, moduleNode.getParentId(), moduleNode.getModuleName(), true, true,null);
        boolean b = moduleMapper.insertNode(module) > 0;
        System.out.println(module.getId());
        moduleNode.setModuleId(module.getId());
        boolean b1 = moduleMapper.insertModule(moduleNode) > 0;
        return b && b1;
    }

    @Override
    @Transactional
    public boolean deleteModuleNode(String ids) {
        boolean b = moduleMapper.deleteModuleNode(ids) > 0;
        boolean b1 = moduleMapper.deleteModule(ids) > 0;
        return  b && b1;
    }
}
